<template>
  <div class="box">
    <div class="selectBox">
      <div>
        <el-tooltip class="item" effect="dark" content="新增" placement="left" v-if="activeName == 'first'&&menuArr.includes('角色组新增')">
          <el-button icon="el-icon-plus" size="mini" @click="addDrawerForm"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="新增" placement="left" v-if="activeName == 'second'&&menuArr.includes('岗位新增')">
          <el-button icon="el-icon-plus" size="mini" @click="addDrawerForm"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="新增" placement="left" v-if="activeName == 'three'&&menuArr.includes('系统新增')">
          <el-button icon="el-icon-plus" size="mini" @click="addDrawerForm"></el-button>
        </el-tooltip>
      </div>
    </div>

    <el-tabs v-model="activeName" @tab-click="handleAcitveClick" type="border-card" style="box-shadow:none;border:none">
      <el-tab-pane label="角色组" name="first">
        <BaseTable :data="cargotableData" :columns="cargotableDataColumns" :tableHeight="tableHeight" :pagination="false" :loading="loading"></BaseTable>
      </el-tab-pane>
      <el-tab-pane label="岗位" name="second">
        <BaseTable :data="cargotableData1" :columns="cargotableDataColumns1" :tableHeight="tableHeight" :pagination="false" :loading="loading"></BaseTable>
      </el-tab-pane>
      <el-tab-pane label="系统" name="three">
        <BaseTable :data="cargotableData2" :columns="cargotableDataColumns2" :tableHeight="tableHeight" :pagination="false" :loading="loading"></BaseTable>
      </el-tab-pane>
    </el-tabs>

    <div class="page">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryAll.startpage" :page-sizes="[10, 15, 20, 25, 30]" :page-size="queryAll.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="totalNum"></el-pagination>
    </div>
    <!-- 角色组成员列表 -->
    <el-drawer title="角色成员" :visible.sync="roleGrounpVisible" size="30%" :before-close="handleCloseb">
      <div class="search_input">
        <el-input placeholder="搜索角色名称" v-model="roleGrounpKey" style="width:150px; margin-right:16px" size="mini" clearable></el-input>
        <el-button class="btn_search" size="mini" type="primary" icon="el-icon-search" @click="searchRoleName">查询</el-button>
      </div>

      <BaseTable :data="roleData" :columns="roleDataColumns" :height="tableHeight" :tableHeight="tableHeight" :pagination="false"></BaseTable>
      <div class="demo-drawer__footer">
          <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="roleGrounpPagination.total" :current-page="roleGrounpPagination.currentPage" :page-size="roleGrounpPagination.pageSize" :page-sizes="[10, 15, 30, 50]" @size-change="roleGrounpPaginationSizeChange" @current-change="roleGrounpPaginationCurrentChange"></el-pagination>
      </div>
    </el-drawer>
    <!-- 角色组新增编辑 -->
    <el-drawer :before-close="handleClose" :title="flagRole ? '新增角色组信息' : '修改角色组信息'" :visible.sync="drawerRole" direction="rtl" size="30%">
      <el-form :model="roleForm" :rules="postRules" ref="rolerefs" label-width="120px" style="padding:20px">
        <el-form-item label="角色组名称：" prop="groupName">
          <el-input v-model="roleForm.groupName"></el-input>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="roleForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="排序号：" prop="sortNum">
          <el-input v-model="roleForm.sortNum"></el-input>
        </el-form-item>
        <div class="demo-drawer__footer">
          <el-button type="primary" @click="submitRole()" size="mini">保存</el-button>
        </div>
      </el-form>
    </el-drawer>
    <!-- 岗位新增编辑 -->
    <el-drawer :before-close="handleClose" :title="flagPost ? '新增岗位信息' : '修改岗位信息'" :visible.sync="drawerPost" direction="rtl" size="30%">
      <el-form :model="postForm" :rules="postRules" ref="postrefs" label-width="100px" style="padding:20px">
        <el-form-item label="岗位名称：" prop="postName">
          <el-input v-model="postForm.postName"></el-input>
        </el-form-item>
        <div class="demo-drawer__footer">
          <el-button type="primary" @click="submitPost()" size="mini">保存</el-button>
        </div>
      </el-form>
    </el-drawer>
    <!-- 系统新增编辑 -->

    <el-drawer :before-close="handleClose" :title="flagSystem ? '新增系统信息' : '修改系统信息'" :visible.sync="drawerSystem" direction="rtl" size="30%">
      <el-form :model="systemForm" :rules="postRules" ref="systemRefs" label-width="100px" style="padding:20px">
        <el-form-item label="系统名称：" prop="systemName">
          <el-input v-model="systemForm.systemName"></el-input>
        </el-form-item>
          <el-form-item label="系统编码：" prop="systemCode">
          <el-input v-model="systemForm.systemCode"></el-input>
        </el-form-item>
        <div class="demo-drawer__footer">
          <el-button type="primary" @click="submitSystem()" size="mini">保存</el-button>
        </div>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import Utils from "@/libs/Utils.js"
import BaseTable from '@/components/BaseTable'
export default {
  components: {
    BaseTable
  },
  name: 'systemGeneral',
  data() {
    return {
      oldVal:{},
      cargotableDataColumns: [
        {
          prop: 'groupName',
          label: '角色组名称'
        },
        {
          prop:'sortNum',
          label:'排序号'
        },
        {
          prop: 'remark',
          label: '备注'
        },
        {
          label: '操作',
          fixed: 'right',
          align: 'center',
          width: 240,
          render: (h, params) => {
            return h(
              'div',

              [
                h('el-button', {
                  props: {
                    size: 'mini'
                  },

                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML: `<span style='color:#0B6CD6;display: ${this.menuArr.includes('角色成员')?"block":"none"}'><i class='iconfont icon-1-05'></i><span  style='padding-left:5px;'>角色成员</span></span>`
                  },
                  on: {
                    click: () => {
                      click: this.openRoleInGroup(params.row)
                    }
                  }
                }),
                h('el-button', {
                  props: {
                    size: 'mini'
                  },

                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML: `<span style='color:#0B6CD6;display: ${this.menuArr.includes('角色组编辑')?"block":"none"}'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>编辑</span></span>`
                  },
                  on: {
                    click: () => {
                      click: this.handleEditRole(params.row)
                    }
                  }
                }),
                h('el-button', {
                  props: {
                    size: 'mini'
                  },

                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML: `<span style='color:#0B6CD6;display: ${this.menuArr.includes('角色组删除')?"block":"none"}'><i class='iconfont icon-1-08'></i><span  style='padding-left:5px;'>删除</span></span>`
                  },
                  on: {
                    click: () => {
                      click: this.deleteRoleGroup(params.row)
                    }
                  }
                })
              ]
            )
          }
        }
      ],
      cargotableData: [],
      cargotableDataColumns1: [
        {
          prop: 'postCode',
          label: '岗位编码'
        },
        {
          prop: 'postName',
          label: '岗位名称'
        },
        {
          label: '操作',
          fixed: 'right',
          align: 'center',
          width: 100,
          render: (h, params) => {
            return h(
              'div',

              [
                h('el-button', {
                  props: {
                    size: 'mini'
                  },

                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML:
                      `<div style="display: ${this.menuArr.includes('岗位编辑')?"block":"none"}"><i class='iconfont icon-liebiaotubiao_liebiaobianji' style='color:#2166B2'></i>编辑</div>`
                  },
                  on: {
                    click: () => {
                      click: this.handleEditPost(params.row)
                    }
                  }
                })
              ]
            )
          }
        }
      ],
      cargotableData1: [],
      cargotableDataColumns2: [
        {
          prop: 'systemCode',
          label: '系统编码'
        },
        {
          prop: 'systemName',
          label: '系统名称'
        },
        {
          label: '操作',
          fixed: 'right',
          align: 'center',
          width: 100,
          render: (h, params) => {
            return h(
              'div',

              [
                h('el-button', {
                  props: {
                    size: 'mini'
                  },

                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML:
                      `<div style="display: ${this.menuArr.includes('系统编辑')?"block":"none"}"><i class='iconfont icon-liebiaotubiao_liebiaobianji' style='color:#2166B2'></i>编辑</div>`
                  },
                  on: {
                    click: () => {
                      click: this.handleEditSystem(params.row)
                    }
                  }
                })
              ]
            )
          }
        }
      ],
      menuFlag:false,
      menuArr:[],
      cargotableData2: [],
      // tableHeight: window.innerHeight - 240,
      queryAll: {
        startpage: 1,
        pagesize: 10
      },
      totalNum: 0,
      activeName: 'first',
      loading: false,
      drawerPost: false, //岗位抽屉
      flagPost: true,
      postRules: {
        postName: [
          {
            required: true,
            message: '请输入岗位名称',
            trigger: 'blur'
          }
        ],
        sortNum: [
          {
            required: true,
            message: '请输入排序号',
            trigger: 'blur'
          }
        ],
        groupName: [
          {
            required: true,
            message: '请输入角色组名称',
            trigger: 'blur'
          }
        ],
        remark: [
          {
            required: true,
            message: '请输入备注',
            trigger: 'blur'
          }
        ],
        systemName: [
          {
            required: true,
            message: '请输入系统名称',
            trigger: 'blur'
          }
        ],
        systemCode: [
          {
            required: true,
            message: '请输入系统编码',
            trigger: 'blur'
          }
        ]
      },
      postForm: {
        postName: '',
      },
      roleData:[],
      roleDataColumns: [
        { prop: 'roleName', label: '角色名称' },
        { prop: 'roleCode', label: '角色编码' },
        {
          label: '操作',
          fixed: 'right',
          align: 'center',
          width: 100,
          render: (h, params) => {
            return h(
              'div',
              [
                h('el-button', {
                  props: {
                    size: 'mini'
                  },

                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML:`<span style='color:#0B6CD6'><i class='iconfont icon-1-08'></i><span  style='padding-left:5px;'>删除</span></span>`
                  },
                  on: {
                    click: () => {
                      click: this.deleteRoleInGroup(params.row)
                    }
                  }
                })
              ]
            )
          }
        }
      ],
      roleGrounpVisible:false,
      roleGrounpKey:'',
      roleGrounpId:'',
      roleGrounpPagination:{
        currentPage:1,
        pageSize:10,
        total:0
      },
      //角色组表单
      roleForm: {
        groupName: '',
        remark: '',
        sortNum:''
      },
      drawerRole: false,
      flagRole: true,

      //系统表单
      systemForm: {
        systemName: '',
        systemCode: ''
      },
      flagSystem: true,
      drawerSystem: false
    }
  },
  async activated() {
    var menuArr = []
    var menuId = ""
    if(localStorage.getItem("menuArr")){
      menuArr = JSON.parse(localStorage.getItem("menuArr"))
    }
    menuArr.map(item=>{
      item.children.map(v=>{
        if(window.location.href.includes(v.url)){
          menuId = v.id
        }
      })
    })

    if(menuId){
      this.menuArr = []
      await this.$http.get(`/${this.$ServiceName}/api/external/sysmenubtn/listresourcebtnbyid?menuId=${menuId}`,{ timeout: 30000,})
              .then(res => {
                res.data.data.map(item=>{
                  this.menuArr.push(item.resourceName)
                })

              }).catch((error)=>{})
    }
     if(this.$store.state.app.searchResouce =="menu"){
      this.getRoleList()
    }
  },
  computed:{
     tableHeight() {
      return this.$store.state.tableHeight - 40
    },
  },
  methods: {
    searchRoleName(){
      this.roleGrounpPagination.currentPage=1
      this.loadRoleGrounpData()
    },
    roleGrounpPaginationSizeChange(val){
      this.roleGrounpPagination.pageSize=val
      this.loadRoleGrounpData()
    },
    roleGrounpPaginationCurrentChange(val){
      this.roleGrounpPagination.currentPage=val
      this.loadRoleGrounpData()
    },
    openRoleInGroup(row){
      this.roleGrounpVisible=true
      this.roleGrounpId=row.id
      this.loadRoleGrounpData()
    },
    async loadRoleGrounpData(){
      const res = await this.$http.get(
        `/${this.$ServiceName}/api/external/sysrolegroup/${this.$version}/selectrolelist?startpage=${this.roleGrounpPagination.currentPage}&roleName=${this.roleGrounpKey}&pagesize=${this.roleGrounpPagination.pageSize}&id=${this.roleGrounpId}`
      )
      console.log('role',res.data.data)
      this.roleData=res.data.data.pages
      this.roleGrounpPagination.pageSize=res.data.data.pageSize
      this.roleGrounpPagination.currentPage=res.data.data.pageNum
      this.roleGrounpPagination.total=res.data.data.totalNum
    },
    deleteRoleInGroup(row){
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(
          `/${this.$ServiceName}/api/external/sysrolegroup/${this.$version}/updategroupid?id=${row.id}`
        ).then(res=>{
          this.$message.success(res.data.msg);
          this.loadRoleGrounpData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    deleteRoleGroup(row){
      this.$confirm('此操作将永久删除该角色组, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete(
            `/${this.$ServiceName}/api/external/sysrolegroup/${this.$version}/deletebyid?id=${row.id}`
          ).then(res=>{
            this.$message.success(res.data.msg);
            this.getRoleList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    handleAcitveClick(tab, event) {
      let activeName = tab.label
      switch (activeName) {
        case '角色组':
          this.queryAll.startpage = 1
          this.queryAll.pagesize = 10
          this.getRoleList()
          // console.log(activeName)
          // console.log(this.activeName)
          break
        case '岗位':
          this.queryAll.startpage = 1
          this.queryAll.pagesize = 10
          this.getPostList()
          // console.log(activeName)
          // console.log(this.activeName)
          break
        case '系统':
          this.queryAll.startpage = 1
          this.queryAll.pagesize = 10
          this.getSystemList()
          // console.log(activeName)
          // console.log(this.activeName)
          break
      }
    },
    handleCloseb(done) {
      done()
    },
    handleClose(done) {
      if(!Utils.compareData(this.oldVal,this.roleForm)){
        this.$confirm('修改的数据未保存，是否关闭？')
                .then(_ => {
                  done()
                })
                .catch(_ => { })
      }else{
        done()
      }
      // this.$confirm('确定是否关闭？')
      //   .then(_ => {
      //     done()
      //
      //
      //   })
      //   .catch(_ => { })
    },
    addDrawerForm() {
      if (this.activeName == 'second') {
        // console.log('岗位')
        this.flagPost = true
        this.drawerPost = true
        delete this.postForm.id

        this.$nextTick(() => {
          this.postForm = {
            postName: ''
          }
          this.$refs.postrefs.resetFields()
        })
      } else if (this.activeName == 'first') {
        // console.log('jiaosezu')
        this.flagRole = true
        this.drawerRole = true

        this.$nextTick(() => {
          this.roleForm = {
            groupName: '',
            remark: '',
            sortNum:''
          }
          this.oldVal = JSON.parse(JSON.stringify(this.roleForm))
          this.$refs.rolerefs.resetFields()
        })
      } else {
        // console.log('系统')
        this.flagSystem = true
        this.drawerSystem = true

        this.$nextTick(() => {
          this.systemForm = {
            systemName: '',
            systemCode: ''

          }
          this.$refs.systemRefs.resetFields()
        })
      }
    },

    //获取岗位数据
    async getPostList() {
      this.loading = true
      const res = await this.$http.get(
        `/${this.$ServiceName}/api/external/sysdeptpost/selectbypage`,
        {
          params: this.queryAll
        }
      )
      if (res.data.code != '0000') {
        return this.$message.error(res.data.msg)
        this.loading = false
      }
      // console.log(res.data.data.pages)

      this.cargotableData1 = res.data.data.pages

      this.queryAll.startpage = res.data.data.pageNum // 当前页
      this.queryAll.pagesize = res.data.data.pageSize // 每页多少
      this.totalNum = res.data.data.totalNum
      this.loading = false
    },
    //岗位编辑
    handleEditPost(row) {
      this.drawerPost = true
      this.flagPost = false
      this.$nextTick(() => {
        this.$refs.postrefs.resetFields()
        this.postForm.postName = row.postName
        this.postForm.id = row.id
      })
    },
    //系统编辑
    handleEditSystem(row) {
      this.drawerSystem = true
      this.flagSystem = false
      this.$nextTick(() => {
        this.$refs.systemRefs.resetFields()
        this.systemForm.id = row.id
        this.systemForm.systemName = row.systemName
        this.systemForm.systemCode = row.systemCode
      })
    },

    //岗位添加编辑按钮
    submitPost() {
      this.$refs.postrefs.validate(async valid => {
        if (valid) {
          if (this.flagPost) {
            const res = await this.$http.post(
              `/${this.$ServiceName}/api/external/sysdeptpost/insert`,
              this.postForm
            )
            if (res.data.code != '0000') {
              return this.$message.error(res.data.msg)
            }
            this.$message.success(res.data.msg)
            this.getPostList()
            this.drawerPost = false
            // console.log(res)
          } else {
            const res = await this.$http.put(
              `/${this.$ServiceName}/api/external/sysdeptpost/update`,
              this.postForm
            )
            if (res.data.code != '0000') {
              return this.$message.error(res.data.msg)
            }
            this.$message.success(res.data.msg)
            this.getPostList()
            this.drawerPost = false
            // console.log(res)
          }
        } else {
          return false
        }
      })
    },

    //获取角色组
    async getRoleList() {
      this.loading = true
      const res = await this.$http.get(
        `/${this.$ServiceName}/api/external/sysrolegroup/v1/listall`,
        {
          params: this.queryAll
        }
      )
      if (res.data.code != '0000') {
        return this.$message.error(res.data.msg)
        this.loading = false
      }
      // console.log(res.data.data.pages)

      this.cargotableData = res.data.data.pages

      this.queryAll.startpage = res.data.data.pageNum // 当前页
      this.queryAll.pagesize = res.data.data.pageSize // 每页多少
      this.totalNum = res.data.data.totalNum
      this.loading = false
    },
    // 角色组添加编辑按钮
    submitRole() {
      this.$refs.rolerefs.validate(async valid => {
        if (valid) {
          if (this.flagRole) {
            const res = await this.$http.post(
              `/${this.$ServiceName}/api/external/sysrolegroup/v1/insert`,
              this.roleForm
            )
            if (res.data.code != '0000') {
              return this.$message.error(res.data.msg)
            }
            this.$message.success(res.data.msg)
            this.getRoleList()
            this.drawerRole = false
            // console.log(res)
          } else {
            const res = await this.$http.put(
              `/${this.$ServiceName}/api/external/sysrolegroup/v1/update`,
              this.roleForm
            )
            if (res.data.code != '0000') {
              return this.$message.error(res.data.msg)
            }
            this.$message.success(res.data.msg)
            this.getRoleList()
            this.drawerRole = false
          }
        } else {
          return false
        }
      })
    },
    //编辑角色组
    handleEditRole(row) {
      this.flagRole = false
      this.drawerRole = true
      this.$nextTick(() => {
        this.$refs.rolerefs.resetFields()
        this.roleForm.id = row.id
        this.roleForm.groupName = row.groupName
        this.roleForm.remark = row.remark
        this.roleForm.sortNum = row.sortNum
        this.oldVal = JSON.parse(JSON.stringify(this.roleForm))
      })



    },
    //系统列表
    async getSystemList() {
      this.loading = true
      const res = await this.$http.get(
        `/${this.$ServiceName}/api/external/syssystemproject/v1/listall`,
        {
          params: this.queryAll
        }
      )
      if (res.data.code != '0000') {
        return this.$message.error(res.data.msg)
        this.loading = false
      }
      // console.log(res.data.data.pages)

      this.cargotableData2 = res.data.data.pages

      this.queryAll.startpage = res.data.data.pageNum // 当前页
      this.queryAll.pagesize = res.data.data.pageSize // 每页多少
      this.totalNum = res.data.data.totalNum
      this.loading = false
    },
    //系统添加编辑
    submitSystem() {
      this.$refs.systemRefs.validate(async valid => {
        if (valid) {
          if (this.flagSystem) {
            const res = await this.$http.post(
              `/${this.$ServiceName}/api/external/syssystemproject/v1/insert`,
              this.systemForm
            )
            if (res.data.code != '0000') {
              return this.$message.error(res.data.msg)
            }
            this.$message.success(res.data.msg)
            this.getSystemList()
            this.drawerSystem = false
          } else {
            const res = await this.$http.put(
              `/${this.$ServiceName}/api/external/syssystemproject/v1/update`,
              this.systemForm
            )
            if (res.data.code != '0000') {
              return this.$message.error(res.data.msg)
            }
            this.$message.success(res.data.msg)
            this.getSystemList()
            this.drawerSystem = false
          }
        } else {
          return false
        }
      })
    },
    //分页
    handleSizeChange(val) {
      this.queryAll.pagesize = val

      switch (this.activeName) {
        case 'first':
          this.getRoleList()
          break
        case 'second':
          this.getPostList()
          break
        case 'three':
          this.getSystemList()
          break
      }
    },
    handleCurrentChange(val) {
      this.queryAll.startpage = val
      switch (this.activeName) {
        case 'first':
          this.getRoleList()
          break
        case 'second':
          this.getPostList()
          break
        case 'three':
          this.getSystemList()
          break
      }
    }
  }
}
</script>

<style lang="less" scoped>
.selectBox {
  justify-content: space-between;
  display: flex;
  flex-direction: row-reverse;
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-left: none;
  line-height: 28px;
  height: 37px;
  padding-top: 11px;
  padding-left: 14px;
  padding-right: 20px;
}
/deep/ .el-drawer__header {
  margin-bottom: 0;
  padding: 16px;
  border-bottom: 1px solid gainsboro;
}
/deep/.el-tabs--border-card > .el-tabs__content {
  padding: 0 !important;
}
.page {
  background: #ffffff;
  text-align: right;
  border-radius: 0 0 4px 4px;
  padding: 5px 20px;
}
//抽屉底部样式
.demo-drawer__footer {
  text-align: right;
  padding-right: 20px;
  border-top: 1px solid #c8cfde;
  background-color: #f5f7fa;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  line-height: 50px;
}
.box {
      border: 1px solid #e1e4eb;
      border-radius: 4px 4px 0 0;
      border-top: none;
    }
    .search_input {
    padding: 10px 20px 10px 20px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .el-input {
      width: 150px;
    }
    }
</style>
